package com.yhc.server.interceptor;

import com.yhc.server.config.RefreshConfig;
import com.yhc.server.consts.RedisPrefixKey;
import com.yhc.server.consts.RequestHeader;
import com.yhc.server.exception.SBFServiceException;
import com.yhc.server.exception.ErrorCodeEnum;
import com.yhc.server.plugin.RedisService;
import com.yhc.server.service.UserCacheService;
import com.yhc.common.dto.UserCacheInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Date;
import java.util.List;

/**
 * 用户校验
 */
@Slf4j
@Configuration
@Order(2)
public class HeaderInterceptor implements HandlerInterceptor {

    @Autowired
    RefreshConfig refreshConfig;
    @Autowired
    UserCacheService userCacheService;
    @Autowired
    RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("# HeaderInterceptor come in");
        validHeader(request);
        setUserCache(request);
        return true;
    }

    /**
     * 设置用户本地线程信息
     *
     * @param request
     */
    private void setUserCache(HttpServletRequest request) {
        List<String> noAuthInterface = refreshConfig.getNoAuthInterface();
        String uri = request.getRequestURI();
        if (noAuthInterface.contains(uri)) {
            return;
        }

        // 获取登录态
        String token = request.getHeader(RequestHeader.token);
        log.warn("# user tk1: {}", token);
        if (StringUtils.isBlank(token)) {
            throw new SBFServiceException(ErrorCodeEnum.EXCEPTION_USER_NO_LOGIN);
        }
        token = token.replace("Bearer ", "");

        // 校验登录态
        String userId = redisService.get(String.format(RedisPrefixKey.LOGIN_USER_TOKEN, token));
        if (StringUtils.isBlank(userId)) {
            throw new SBFServiceException(ErrorCodeEnum.EXCEPTION_USER_NO_LOGIN);
        }
        String realToken = redisService.get(String.format(RedisPrefixKey.LOGIN_USER_TOKEN, userId));
        if (!StringUtils.equals(token, realToken)) {
            throw new SBFServiceException(ErrorCodeEnum.EXCEPTION_USER_SQUEEZE_LOGIN);
        }

        // 缓存登录信息
        UserCacheInfo user = UserCacheInfo.builder().userId(Long.parseLong(userId)).build();
        userCacheService.setUser(user);
    }

    /**
     * 请求头校验
     *
     * @param request
     */
    private void validHeader(HttpServletRequest request) {
        String requestId = request.getHeader(RequestHeader.REQUEST_ID);
        String txTime = request.getHeader(RequestHeader.TX_TIME);
        log.info("# request headers: requestId:{}, txTime:{}", requestId, txTime);

        if (StringUtils.isBlank(requestId)) {
            throw new SBFServiceException(ErrorCodeEnum.EXCEPTION_REQUIRED_PARAMS_NO_REQUEST_ID);
        }
        if (StringUtils.isBlank(txTime)) {
            throw new SBFServiceException(ErrorCodeEnum.EXCEPTION_REQUIRED_PARAMS_NO_TX_TIME);
        }
        long dif = (new Date().getTime() - Long.parseLong(txTime)) / 1000 / 60;
        if (dif > 1) {
            throw new SBFServiceException("过期请求");
        }
    }

}
